package tools;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;

import javax.imageio.ImageIO;

public class ByteArrayIterable implements Iterable<byte[]> {

	private final int size;
	private final byte[] array;
	private final int packets;

	public ByteArrayIterable(byte[] array, int size) {
		this.array = array;
		this.size = size;
		this.packets = array.length/size;
	}

	public Iterator<byte[]> iterator() {
		return new Iterator<byte[]>() {
			private int arrayIndex = 0;

			public boolean hasNext() {
				return ((arrayIndex)*size < array.length);
			}

			public byte[] next() {
				// cas normal
				if((arrayIndex+1)*size < array.length) {
					byte[] buf = new byte[size];
					System.arraycopy(array, arrayIndex*size, buf, 0, size);
					arrayIndex++;
					return buf;
				}
				// dernier cas
				else {
					int remaning = array.length - arrayIndex*size;
					byte[] buf = new byte[remaning];
					System.arraycopy(array, arrayIndex*size, buf, 0, remaning);
					arrayIndex++;
					return buf;
				}
			}

			public void remove() {
				throw new UnsupportedOperationException();
			}
		};
	}
	
	public int getPackets() { return packets; }

	public static void main(String[] a) {
		
		BufferedImage img = null;
		try {
			img = ImageIO.read(new File("test\\test0.bmp"));
		} catch (IOException e1) {
			e1.printStackTrace();
		}
		
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		byte[] imageInByte = null;
		try {
			ImageIO.write(img, "bmp", baos);
			baos.flush();
			imageInByte = baos.toByteArray();
			baos.close();
		} catch (IOException e1) {
			e1.printStackTrace();
		}
		
		byte[] header = BMPUtils.getHeader(imageInByte);
		int header_size = header.length;
		byte[] data = BMPUtils.getData(header_size, imageInByte);
		
		System.out.println("Header:");
		ByteArrayIterable test_iterable = new ByteArrayIterable(header, 1024);
		for (byte[] tab : test_iterable)
			System.out.println(new String(tab));
		
		System.out.println("Data:");
		test_iterable = new ByteArrayIterable(data, 1024);
		int i = 0;
		for (byte[] tab : test_iterable) {
			System.out.println(i+" "+tab.length+" "+new String(tab));
			i++;
		}
	}
}
